package flex.cc.uac.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.base.Preconditions;
import flex.cc.PublicUtil;
import flex.cc.base.constant.GlobalConstant;
import flex.cc.base.dto.LoginAuthDto;
import flex.cc.base.enums.ErrorCodeEnum;
import flex.cc.uac.dao.UacActionDao;
import flex.cc.uac.dao.UacRoleActionDao;
import flex.cc.uac.entity.UacActionEntity;
import flex.cc.uac.entity.UacMenuEntity;
import flex.cc.uac.exceptions.UacBizException;
import flex.cc.uac.service.UacActionService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.AntPathMatcher;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;


@Service("uacActionService")
@Slf4j
public class UacActionServiceImpl extends ServiceImpl<UacActionDao, UacActionEntity> implements UacActionService {

    private AntPathMatcher antPathMatcher = new AntPathMatcher();

    @Autowired
    private UacActionDao uacActionDao;
    @Autowired
    private UacRoleActionDao uacRoleActionDao;

    @Override
    @Transactional(readOnly = true, rollbackFor = Exception.class)
    public IPage<UacActionEntity> queryActionListWithPage(UacActionEntity uacActionEntity) {

        QueryWrapper<UacActionEntity> queryWrapper = new QueryWrapper<UacActionEntity>()
                .eq(PublicUtil.isNotEmpty(uacActionEntity.getActionName()),
                        "action_name",
                        uacActionEntity.getActionName())
                .eq("menu_id",uacActionEntity.getMenuId())
                .orderByDesc("update_time");
        IPage<UacActionEntity> page = new Page<>(uacActionEntity.getPageNum(),uacActionEntity.getPageSize());
        return this.page(page,queryWrapper);
    }

    @Override
    public int deleteActionById(Long actionId) {
        //查询该角色下是否有用户绑定, 有的话提醒不能删除
        if (null == actionId) {
            throw new IllegalArgumentException("权限ID不能为空");
        }
        UacActionEntity uacAction = uacActionDao.selectById(actionId);
        if (uacAction == null) {
            log.error("找不到权限信息 actionId={}", actionId);
            throw new UacBizException(ErrorCodeEnum.UAC10014001, actionId);
        }
        // 删除角色权限表数据  不查询了 直接删除了
        Map<String,Object> map = new HashMap<String,Object>();
        map.put("action_id",actionId);
        uacRoleActionDao.deleteByMap(map);
        return uacActionDao.deleteById(actionId);
    }

    @Override
    public void saveAction(UacActionEntity uacAction, LoginAuthDto loginAuthDto) {
        Long menuId= uacAction.getMenuId();
        Preconditions.checkArgument(PublicUtil.isNotEmpty(menuId), "菜单不能为空");
        uacAction.setMenuId(menuId);
        uacAction.setUpdateInfo(loginAuthDto);
        if (uacAction.isNew()) {
            uacActionDao.insert(uacAction);
        } else {
            int result = uacActionDao.updateById(uacAction);
            if (result < 1) {
                throw new UacBizException(ErrorCodeEnum.UAC10014003);
            }
        }
    }



    @Override
    public List<UacActionEntity> listActionListByRoleId(Long roleId) {
        return uacActionDao.listActionListByRoleId(roleId);
    }

    @Override
    public List<UacActionEntity> listActionList(List<UacMenuEntity> uacMenus) {
        return uacActionDao.listActionList(uacMenus);
    }

    @Override
    @Transactional(readOnly = true, rollbackFor = Exception.class)
    public List<Long> getCheckedActionList(Long roleId) {
        if (roleId == null) {
            throw new UacBizException(ErrorCodeEnum.UAC10012001);
        }
        return uacActionDao.getCheckedActionList(roleId);
    }

    @Override
    public List<UacActionEntity> getOwnActionListByUserId(Long userId) {
        if (userId == null) {
            throw new UacBizException(ErrorCodeEnum.UAC10011001);
        }
        List<UacActionEntity> uacActionList;
        if (Objects.equals(userId, GlobalConstant.Sys.SUPER_MANAGER_USER_ID)) {
            // 获取全部权限信息
            uacActionList = this.list();
        } else {
            uacActionList = uacActionDao.getOwnUacActionListByUserId(userId);
        }
        return uacActionList;
    }


    @Override
    public UacActionEntity matchesByUrl(String requestUrl) {

        List<UacActionEntity> uacActionList =  this.list();
        for (UacActionEntity uacAction : uacActionList) {
            String url = uacAction.getUrl();
            if (StringUtils.isEmpty(url)) {
                continue;
            }
            if (antPathMatcher.match(url, requestUrl)) {
                return uacAction;
            }
        }
        return null;
    }


}